package com.cicv.oss.config.adapter.controller;

import com.cicv.oss.config.adapter.entity.OssConfigInfo;
import com.cicv.oss.config.infra.config.OssConfig;
import com.cicv.oss.config.infra.config.util.MyFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("/ros")
public class RosController {

//    @Autowired
//    private ResourceLoader resourceLoader;

    @GetMapping("/config")
    public void config(HttpServletResponse response) {
        try {
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("config.yaml", "utf-8"));
            byte[] buffer = new byte[10000];
//            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:config.yaml");
//            InputStream inputStream = resource.getInputStream();
            InputStream inputStream = Files.newInputStream(Paths.get("/mnt/disk001/oss-config/yaml/config.yaml"));
            ServletOutputStream outputStream = response.getOutputStream();
            for (int bytesRead = inputStream.read(buffer); bytesRead >= 0; bytesRead = inputStream.read(buffer)) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/configString")
    public String configString() {
        try {
            InputStream inputStream = Files.newInputStream(Paths.get("/mnt/disk001/oss-config/yaml/config.yaml"));
            return MyFileUtil.read(inputStream, 10000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @GetMapping("/configString2")
    public String configString2() {
        try {
            InputStream inputStream = Files.newInputStream(Paths.get("/mnt/disk001/oss-config/yaml/config2.yaml"));
            return MyFileUtil.read(inputStream, 10000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
